package cn.sangyy.gift.service.impl;

import cn.sangyy.gift.common.util.VerifyCodeUtils;
import cn.sangyy.gift.common.util.code.CodeEnum;
import cn.sangyy.gift.exception.BusinessException;
import cn.sangyy.gift.service.IPhoneVerifyCodeService;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author SangYY
 * @date: 2023/06/23/15:35
 */
@Service
public class PhoneVerifyCodeServiceImpl implements IPhoneVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${alysms.accesskeyid}")
    private String ACCESS_KEY_ID;
    @Value("${alysms.secret}")
    private String SECRET;
    @Value("${alysms.signname}")
    private String SIGN_NAME;
    @Value("${alysms.templatecode}")
    private String TEMPLATE_CODE;

    @Override
    public void sendVerifyCode(String phone, String key) {
        String phoneCode = (String) redisTemplate.opsForValue().get(key);
        //验证码存在
        if(StringUtils.isNotBlank(phoneCode)){
            //判断是否过重新获取验证码的时间
            Long expireTime = redisTemplate.getExpire(key);
            if(expireTime != null && expireTime != -1 && expireTime != -2){
                System.out.println(expireTime);
                if(expireTime - 240 > 0){ //没到重发时间，抛个异常
                    throw new BusinessException(CodeEnum.REGISTER_MOBILE_CODE_OFTEN);
                }
            }else {
                throw new BusinessException("网络异常！");
            }
        }else {//验证码不存在
            phoneCode = VerifyCodeUtils.generateVerifyCode(6, "0123456789");
        }
        //设置到redis中去
        redisTemplate.opsForValue().set(key,phoneCode,5, TimeUnit.MINUTES);
        //阿里云短信服务发送短信验证码
//        Sms(phone,phoneCode);
        System.out.println("短信验证码："+phoneCode);

    }
    private void Sms(String phone,String code) {
        /**
         * 连接阿里云：
         *
         * 三个参数：
         * regionId 不要动，默认使用官方的
         * accessKeyId 自己的用户accessKeyId
         * accessSecret 自己的用户accessSecret
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-chengdu",ACCESS_KEY_ID, SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求：
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        // 自定义参数：
        request.putQueryParameter("PhoneNumbers", phone);// 接收短信的手机号
        request.putQueryParameter("SignName", SIGN_NAME);// 短信签名
        request.putQueryParameter("TemplateCode", TEMPLATE_CODE);// 短信模版CODE

        // 构建短信验证码
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }
}
